package day06;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

public class 二叉树中序遍历 {
    /*public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> ret = new ArrayList<>();
        if (root == null) {
            return ret;
        }
        // 左子树，根，右子树
        TreeNode cur = root;
        // 用栈进行维护,先进后出
        Stack<TreeNode> stack = new Stack<>();
        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                // 入栈
                stack.push(cur);
                cur = cur.left;
            }
            // 定义一个临时节点
            TreeNode tmp = stack.pop();
            ret.add(tmp.val);
            cur = tmp.right;
        }
        return ret;

    }*/

    public List<Integer> inorderTraversal(TreeNode root) {
        // 利用递归
        List<Integer> ret = new ArrayList<>();
        digui(root, ret);
        return ret;
    }

    public void digui(TreeNode root, List<Integer> list) {
        if (root == null) {
            return;
        }
        // 左子树
        digui(root.left,list);
        // 添加根节点
        list.add(root.val);
        // 右子树
        digui(root.right,list);
    }
}
